package chances.wechat.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.type.TypeReference;

import chances.wechat.data.PageBean;
import chances.wechat.entity.UserCollection;
import chances.wechat.model.CollectionDelEvent;
import chances.wechat.model.CollectionEmptyEvent;
import chances.wechat.model.CollectionEvent;
import chances.wechat.resp.BaseResponse;
import chances.wechat.resp.ResultResponse;
import chances.wechat.resp.ResultSetResponse;
import chances.wechat.service.CollectionService;
import chances.wechat.service.StbDataService;
import chances.wechat.utils.JSONUtils;
import chances.wechat.utils.RequestUtils;

@RestController
@RequestMapping(value = "/fav")
public class CollectionController extends UserAbstractController {
    private static Logger logger = LoggerFactory.getLogger("contentData");

    @Autowired
    private CollectionService collectionService;

    @Autowired
    StbDataService stbDataService;

    /**
     * 添加用户收藏
     * 
     * @param model
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/add")
    public BaseResponse addCollection(ModelMap model,
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam String stbNo) throws IOException {
        BaseResponse result = new BaseResponse();
        logger.debug(request.getRequestURI());

        UserCollection collection = this.createUserCollection(request);
        if (StringUtils.isBlank(collection.getUserId())
                || StringUtils.isBlank(collection.getContentId())) {
            result.setStatus(VALID_PARAM);
            result.setMessage("lack param");
        } else {
            try {
                this.collectionService.addCollection(collection);

                CollectionEvent event = new CollectionEvent();
                event.setStbNo(stbNo);
                event.setUserCollection(collection);
                this.applicationContext.publishEvent(event);
            } catch (Throwable ex) {
                logger.error("add user history error.", ex);
                result.setStatus(DB_ERROR);
                result.setMessage(ex.getMessage());
            }
        }
        return result;
    }

    /**
     * 批量删除用户收藏
     * 
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/del")
    public ResultResponse<String> batchDelUserCollection(
            @RequestParam String codes, @RequestParam String userId,
            @RequestParam String stbNo) throws IOException {
        ResultResponse<String> result = new ResultResponse<String>();
        result.setStatus(SUCCESS);
        if (StringUtils.isEmpty(codes)) {
            result.setStatus(SYS_ERROR);
            result.setMessage("lack param codes");
            return result;
        }
        String[] codesArr = codes.split(",");
        try {
            this.collectionService.batchDelUserCollection(codesArr, userId);

            CollectionDelEvent event = new CollectionDelEvent();
            event.setStbNo(stbNo);
            event.setCodes(Arrays.asList(codesArr));
            this.applicationContext.publishEvent(event);
        } catch (Throwable ex) {
            result.setStatus(DB_ERROR);
            logger.error("remove user collections error.", ex);
        }
        return result;
    }

    /**
     * 清空用户收藏
     * 
     * @param model
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/clear")
    public BaseResponse clearCollection(@RequestParam String userId,
            @RequestParam String stbNo,
            @RequestParam(required = false, defaultValue = "") String category)
            throws IOException {
        BaseResponse result = new BaseResponse();

        if (StringUtils.isBlank(userId)) {
            result.setStatus(VALID_PARAM);
            result.setMessage("userId is empty");
        } else {
            try {
                this.collectionService.clearCollections(userId, category);
                CollectionEmptyEvent event = new CollectionEmptyEvent();
                event.setStbNo(stbNo);
                this.applicationContext.publishEvent(event);
            } catch (Throwable ex) {
                logger.error("clear user history error.", ex);
                result.setStatus(DB_ERROR);
                result.setMessage(ex.getMessage());
            }
        }
        return result;
    }

    /**
     * 查询用户收藏
     * 
     * @param model
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/list")
    public BaseResponse listCollections(HttpServletRequest request,
            @RequestParam String userId, @RequestParam String stbNo)
            throws IOException {
        ResultSetResponse<UserCollection> result = new ResultSetResponse<UserCollection>();
        try {
            PageBean page = this.getPageBean(request);
            if (stbDataService.sendToStb()) {
                return stbDataService.listCollection(stbNo,
                        page.getCurrentPage(), page.getRecordCount());
            }

            List<UserCollection> collectionList = collectionService
                    .listCollections(userId, null, null, null, null, page);
            result.setResultSet(collectionList);
            result.setPageBean(page);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(500);
            result.setMessage(e.getMessage());
            return result;
        }
    }

    @RequestMapping(value = "/remove")
    public ResultResponse<String> removeCollection(ModelMap model,
            HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String userId = RequestUtils.getParameter(request, "userId", "");
        String contentId = RequestUtils.getParameter(request, "contentId", "");
        ResultResponse<String> result = new ResultResponse<String>();
        result.setResult(contentId);
        result.setStatus(SUCCESS);
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(contentId)) {
            result.setStatus(VALID_PARAM);
        } else {
            try {
                this.collectionService.removeCollection(userId, contentId);
            } catch (Throwable ex) {
                result.setStatus(DB_ERROR);
                logger.error("remove user history error.", ex);
            }
        }
        return result;
    }

    @RequestMapping(value = "/removeCollections")
    public ResultResponse<String> removeCollections(@RequestBody String body,
            HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ResultResponse<String> result = new ResultResponse<String>();
        result.setStatus(SUCCESS);

        try {
            List<UserCollection> userComments = JSONUtils.toObject(body,
                    new TypeReference<List<UserCollection>>() {
                    });
            for (UserCollection userCollection : userComments) {
                if (StringUtils.isNotBlank(userCollection.getUserId())
                        && StringUtils
                                .isNotBlank(userCollection.getContentId()))
                    this.collectionService.removeCollection(
                            userCollection.getUserId(),
                            userCollection.getContentId());
            }

        } catch (Throwable ex) {
            result.setStatus(DB_ERROR);
            logger.error("remove user collections error.", ex);
        }
        return result;
    }

    @RequestMapping(value = "/query")
    public ResultSetResponse<UserCollection> queryCollection(ModelMap model,
            HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String userId = RequestUtils.getParameter(request, "userId", "");
        String contentId = RequestUtils.getParameter(request, "contentId", "");
        ResultSetResponse<UserCollection> result = new ResultSetResponse<UserCollection>();
        result.setStatus(SUCCESS);
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(contentId)) {
            result.setStatus(VALID_PARAM);

        } else {
            try {
                List<UserCollection> collectionList = collectionService
                        .listCollections(userId, contentId);
                result.setResultSet(collectionList);
                result.setPageBean(new PageBean());
            } catch (Throwable ex) {
                result.setStatus(DB_ERROR);

                logger.error("query user history error.", ex);
            }
        }

        return result;
    }

    private UserCollection createUserCollection(HttpServletRequest request) {
        UserCollection collection = new UserCollection();
        collection.setContentId(
                RequestUtils.getParameter(request, "contentId", ""));
        collection.setContentName(
                RequestUtils.getParameter(request, "contentName", ""));
        collection.setContentPoster(
                RequestUtils.getParameter(request, "contentPoster", ""));
        collection.setContentType(
                RequestUtils.getParameter(request, "contentType", ""));
        collection.setPath(RequestUtils.getParameter(request, "path", ""));
        collection.setUserId(RequestUtils.getParameter(request, "userId", ""));
        collection.setCategory(
                RequestUtils.getParameter(request, "category", ""));
        return collection;
    }
}
